

//环形图
require.config({
    paths:{
        'echarts' : '/javascript/home/echart/echarts',
        'echarts/chart/pie' : '/javascript/home/echart/echarts'
    }
});

//    按apr
function showPie_apr(sel,apr){
    var labelTop = {
        normal : {
            color:'#f2060c',
            label : {
                show : false,
                position : 'center',
                formatter : '{b}',
                textStyle: {
                    baseline : 'bottom'
                }
            },
            labelLine : {
                show : false
            }
        }
    };
    var labelFromatter = {
        normal : {
            label : {
                formatter : function (a,b,c){return apr + '%'},
                textStyle: {
                    baseline : 'middle',
                    color:"#f2060c"
                }
            }
        }
    }
    var labelBottom = {
        normal : {
            color: '#ccc',
            label : {
                show : true,
                position : 'center'
            },
            labelLine : {
                show : false
            }
        },
        emphasis: {
            color: 'rgba(0,0,0,0)'
        }
    };
    var window_width = $(".wrap-pie-apr").css('width'),radius;
    if(window_width == '60px'){
        radius = [25, 30];
    }
    if(window_width == '85px'){
        radius = [35, 40];
    }
    require(
        [
            'echarts',
            'echarts/chart/pie' // 使用柱状图就加载bar模块，按需加载
        ],
        function (ec) {
            // 基于准备好的dom，初始化echarts图表
            var myChart = ec.init(document.getElementById(sel));
            option = {
                series : [
                    {
                        type : 'pie',
                        radius : radius,
                        itemStyle : labelFromatter,
                        data : [
                            {name:'剩余', value:100-apr, itemStyle : labelBottom},
                            {name:'已筹', value:apr,itemStyle : labelTop}
                        ]
                    }
                ]
            };
            // 为echarts对象加载数据
            myChart.setOption(option);
        }
    );
}
var sel='';
var apr=0;
$(".wrap-pie-apr").each(function(){
    sel =  $(this).attr('id');
    if($(this).attr('data-apr').length>1){
        apr = $(this).attr('data-apr').split('%')[0];
    }
    showPie_apr(sel,apr);
})

//    按天
function showPie_day(sel,apr,_day){
    var labelTop = {
        normal : {
            color:'#42adfd',
            label : {
                show : false,
                position : 'center',
                formatter : '{b}',
                textStyle: {
                    baseline : 'bottom'
                }
            },
            labelLine : {
                show : false
            }
        }
    };
    var labelFromatter = {
        normal : {
            label : {
                formatter : function (a,b,c){return _day + '天'},
                textStyle: {
                    baseline : 'middle',
                    color:"#42adfd"
                }
            }
        }
    };
    var labelBottom = {
        normal : {
            color: '#ccc',
            label : {
                show : true,
                position : 'center'
            },
            labelLine : {
                show : false
            }
        },
        emphasis: {
            color: 'rgba(0,0,0,0)'
        }
    };
    var window_width = $(".wrap-pie-apr").css('width'),radius;
    if(window_width == '60px'){
        radius = [25, 30];
    }
    if(window_width == '85px'){
        radius = [35, 40];
    }
    require(
        [
            'echarts',
            'echarts/chart/pie' // 使用柱状图就加载bar模块，按需加载
        ],
        function (ec) {
            // 基于准备好的dom，初始化echarts图表
            var myChart = ec.init(document.getElementById(sel));
            option = {
                series : [
                    {
                        type : 'pie',
                        radius : radius,
                        itemStyle : labelFromatter,
                        data : [
                            {name:'', value:100-apr, itemStyle : labelBottom},
                            {name:'', value:apr,itemStyle : labelTop}
                        ]
                    }
                ]
            };
            // 为echarts对象加载数据
            myChart.setOption(option);
        }
    );
}
var _day=0;
$(".wrap-pie-day").each(function(){
    sel =  $(this).attr('id');
    if($(this).attr('data-apr').length>1){
        apr = $(this).attr('data-apr').split('%')[0];
        _day = $(this).attr('data-day');
    }
    showPie_day(sel,apr,_day);
});

//环形图  e
///验证码
//提交
ajax = {
    data:null,
    _post:function(opt){
//        trigger 选择器*
//        form_id 表单ID*
//            url post地址*
//        tips    提示选择器*
//        type     类型
        var trigger = $(opt.trigger);
        var tips = $(opt.tips);
        var url = opt.url;
            tips.text('');
            var sel_name = trigger.text();
            var db = $('#'+opt.form_id+'').serialize();
            if(opt.type == 'reg'){
                if( !$(".check-agree").hasClass('selected')){
                    tips.text('请同意服务协议');
                    return false;
                }
            }
            if(trigger.hasClass('ui-btn-disabled'))return false;
            trigger.addClass('ui-btn-disabled').text('提交中');
            $.post(url,db,function(json){
                if(opt.type == 'reset'){
                    if(json.status == 1){
                        alert(json.info);
                        window.location.href = '/';
                    }else{
                        tips.text(json.info).css('color','green');
                    }
                    return false;
                }
                if(json.status == 1){
                    tips.text(json.info).css('color','green');
                    if(opt.type == 'login'){
                        window.location.href = json.url;
                    }
                    if(opt.type == 'reg' || opt.type == 'address'){
                        window.location.reload();
                    }
                    if(opt.type == 'lostpw'){
                        alert(json.info);
                        window.location.reload();
                    }
                }else{
                    tips.text(json.info);
                    trigger.removeClass('ui-btn-disabled').text(sel_name);
                    $(".code-img").click();
                }
            },'json')
    },
//    发送验证码
    sms:function(opt){
        var sel = $(opt.trigger);
        var url = opt.url;
        sel.on('click',function(){
            if($(this).hasClass('ui-btn-disabled')){return false;}
            $(this).addClass('ui-btn-disabled');
            var phone = $(sel).closest('.ui-form').find($("[name=mobile]")).val();
            $.post(url,{mobile:phone},function(json){
                if(json.status == 1){
                    ajax.btnCountTime(sel,60);
                }else{
                    alert(json.info);
                    sel.addClass('ui-btn-blue').removeClass('ui-btn-disabled');
                }
            },'json')
        })
    },
    //    按钮倒计时
    btnCountTime:function(sel,sec){
        var countTime = setInterval(function(){
            sel.text('重新获取').addClass('ui-btn-disabled');
            sel.text(sec+'秒后重新获取');
            if(sec == 0){
                clearInterval(countTime);
                sel.text('重新获取').removeClass('ui-btn-disabled');
            }
            sec -= 1;
        },1000)
    }

};
//发送验证码
ajax.sms({
    trigger:'.get-code-reg',
    url:'/user/sms_valid'
});
//添加项目发送验证码
ajax.sms({
    trigger:'.get-code-add',
    url:'/project/sms_valid'
});


$(function(){
    //登录
    $('#login-form').validator({
        fields: {
            'username': 'required;',
            'password': 'required;',
            'code': 'required;'
        }
    });

    $("#login-ajax").on('click',function(){
        if($("#login-form").isValid()){
            var db = $("#login-form").serialize();
            $.post('/user/login',db,function(data){
                $(".login-tips").text(data.info);
                if(data.status == 1){
                    window.location.reload();
                }else if(data.status == 2){
                    alert(data.info);
                    $("#h-user").val($("#username").val());
                    $("#h-pass").val($("#pass").val());
                    $("#login-form").hide();
                    $("#wrap-login").hide();
                    $("#wrap-login-bind").show();
                    $("#login-bind-form").show();
                }
            },'json')
        }
    });
    $("#login-ajax-bind").on('click',function(){
        var db = $("#login-bind-form").serialize();
        $.post('/User/bind',db,function(data){
            $(".login-bind-tips").text(data.info);
            if(data.status == 1){
                window.location.reload();
            }
        },'json')
    });
    //注册
    $('#reg-form').validator({
        fields: {
            'email': 'required;',
            'password': 'required;',
            're_password': 'required;',
            'mobile': 'required;',
            'code': 'required;',
            'auth_code': 'required;'
        }
    });
    $("#register").on('click',function(){
        if($("#reg-form").isValid()){
        ajax._post({
            trigger:'#register',
            type:'reg',
            form_id:'reg-form',
            url:'/user/register',
            tips:'.tips'
        });
        }
    });
    //修改密码
    $('#form-pwd').validator({
        fields: {
            'old_pwd': 'required;',
            'new_pwd': 'required;',
            'repeat_pwd': 'required;'
        }
    });
    $("#change-pwd").on('click',function(){
        if($("#form-pwd").isValid()){
        ajax._post({
            trigger:'#change-pwd',
            form_id:'form-pwd',
            url:'/user/password',
            tips:'.pwd-tips'
        });
        }
    });
    $('#reset-pwd').validator({
        fields: {
            'old_pwd': 'required;',
            'new_pwd': 'required;',
            'repeat_pwd': 'required;',
            'code': 'required;'
        }
    });
    $("#reset-pwd").on('click',function(){
        if($("#form-reset-pwd").isValid()){
            ajax._post({
                trigger:'#reset-pwd',
                type:'reset',
                form_id:'form-reset-pwd',
                url:'/user/reset',
                tips:'.pwd-tips'
            });
        }
    });
//忘记密码
    $('#forget-form').validator({
        fields: {
            'email': 'required;email;'
        }
    });
    $("#lost-ajax").on('click',function(){
        if($("#forget-form").isValid()){
            ajax._post({
                trigger:"#lost-ajax",
                form_id:'forget-form',
                type:'lostpw',
                tips:'.lost-tips',
                url:'/user/reset_password'
            });
        }
    });
//添加新地址
    $('#set-add').validator({
        fields: {
            'consignee': 'required;',
            'mobile': 'required;',
            'address': 'required;'
        }
    });
    $("#save-add").on('click',function(){
        if($("#set-add").isValid()){
            ajax._post({
                trigger:"#save-add",
                form_id:'set-add',
                tips:'.add_tips',
                type:'address',
                url:'/User/address'
            });
        }
    });

    //模拟radio
    $(".ui-radio").on('click',function(){
        if($(this).hasClass('selected')){
            $(this).removeClass('selected');
        }else{
            $(this).parents('.form-radio').find('.ui-radio').removeClass('selected');
            $(this).addClass('selected');
        }
        $(this).children().prop('checked','true');
    });
//    添加地址
    $('.add-address').on('click',function(){
        $("#address-type").val('add');
        $("#add_address").modal('show');
    });
//    删除地址
    $(".sel-address").on('click',function(){
        var id = $(this).attr('data-id');
        var r=confirm("确认删除该选项吗？");
        if (r==true)
        {
            $.post('/User/address',{id:id,type:'del'},function(data){
                alert(data.info);
                window.location.reload();
            },'json')
        }else{return false;}
    });
//    设置默认地址
    $(".set-del-add").on('click',function(){
        var id = $(this).attr('data-id');
        var r=confirm("确认设置本地址为默认地址？");
        if (r==true)
        {
            $.post('/User/address',{id:id,type:'def'},function(data){
                alert(data.info);
                window.location.reload();
            },'json')
        }else{return false;}
    });
//    修改地址
    $(".reset-add").on('click',function(){
        var id = $(this).attr('data-id');
        $("#address-type").val('edit');
        $("#add-id").val(id);
        $("#add_address").modal('show');
        $.post('/User/address',{id:id,type:'load'},function(data){
            $(".province-list").val(data.province);

            var pro_id = $(".province-list").find("option:selected").attr('rel');
            add_city(pro_id);
            $(".city-list").val(data.city);
            $('[name=consignee]').val(data.consignee);
            $('[name=mobile]').val(data.mobile);
            $('[name=address]').val(data.address);
            $('[name=zip]').val(data.zip);
            $(".int-slt-province .dr-text").text(data.province);
            $(".int-slt-city .dr-text").text(data.province);
        },'json')
    });
//发起人checkbox
    $(".btn-type").on('click',function(){
        if($(this).hasClass('current')){
            $(this).removeClass('current');
        }else{
            $(this).parents('.wrap-btn-type').find('.btn-type').removeClass('current');
            $(this).addClass('current');
        }
        $(this).children().prop('checked','true');
    });
    //添加喜欢
    $("#add-like").on('click',function(){
        var db = $(this).attr('data-id');
        $.post('/User/fav_add',{id:db},function(data){
            if(data.status==1){
                $("#add-like").addClass('ui-btn-disabled').removeClass('ui-btn-red');
                $(".like-text").text('不再喜欢')
            }else if(data.status==2){
                $("#add-like").addClass('ui-btn-red').removeClass('ui-btn-disabled');
                $(".like-text").text('喜欢')
            }else{
                alert(data.info);
            }
        },'json')
    });
//发货设置
    $(".bnt-send-goods").on('click',function(){
        $(".send-goods-dialog").modal('show');
    });
    //删除喜欢
    $(".del-like").on('click',function(){
        var id = $(this).attr('data-id');
        var r=confirm("确认删除该选项吗？");
        if (r==true)
        {
            $.post('/User/fav_del',{id:id},function(data){
                    alert(data.info);
                    window.location.reload();
            },'json')
        }else{return false;}
     });
    //下拉点击  slecte事件

    $(".dropdown-menu").on('click','li',function(){
        if($(this).parent('.dropdown-menu').hasClass('nojs')){
            return false;
        }
        var slttext = $(this).text();
        var showdom = $(this).parent('.dropdown-menu').prev('[data-toggle]');
        //判断tagName
        var tgn = showdom[0].nodeName;
        if(tgn=='A'){
            showdom.find(".dr-text").text(slttext);
        }else if(tgn=="BUTTON"){
            showdom.prev('.int-slt').text(slttext)
        }
//        传值
        var ipt = $(this).parent(".dropdown-menu").siblings(".select-val");
        var _this_val = $(this).attr("data-val");
        ipt.val(_this_val);
    });
//    返回头部
    $(".back-top").on('click',function(){
        $('html,body').animate({scrollTop:'0px'},500);
        return false;
    });
//    help icon
    $(".panel-heading").click(function(){
        if($(this).hasClass('collapsed')){
            $(this).children('.help-icon-up').show();
        }else{
            $(this).children('.help-icon-up').hide();
        }
    });
//    验证码
    $(".code-img").on('click',function(){
        $(this).attr('src', '/index/verify_code?rand='+Math.random())
    });
    //切换地区
    $(".province-list").on('change',function(){
       var
           id=$(this).find("option:selected").attr("rel");
        add_city(id);
    });
    function add_city(id){
        var evalStr="regionConf.r"+id+".c";
        //var html = '<span class="dr-text">选择城市</span>';
        if(id==0)
        {
            var html = '<option class="items" rel="0">请选择城市</option>';
        }else{
            var regionConfs=eval(evalStr);
            evalStr+=".";
            var html = '<option class="items" rel="0">请选择城市</option>';
            for(var key in regionConfs)
            {
                html+='<option class="items" rel="'+ eval(evalStr+key+".i") +'">'+eval(evalStr+key

                +".n")+'</option>'
            }
        }
        $(".city-list").html(html);
    }
    $("#link-forget").on('click',function(){
        $("#login-wrap").hide();
        $("#forget-wrap").show();
    })
    //发起项目
    $("#btn_create_project").on('click',function(){
        var _title =$('[name=name]').val();
        var _money = $("[name=limit_price]").val();
        var _days = $("[name=deal_days]").val();
        var _city = $("[name=city]").val();
        var _province = $("[name=province]").val();
        var _cate_id = $(".btn-type").hasClass('current');
        var _brief =$("[name=brief]").val();
        var _upload_image = $("#upload_image").attr('src');
        var _reg_num = /^\d+$/;
        var _reg_money = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
        if(_title.length <= 0 || _title.length > 40){alert("请输入项目名称，不得超过40个字");return false;}
        if(_money<500){alert("筹资金额不得少于500元");return false;}
        if(!_reg_money.test(_money)){alert("请输入正确金额，最多保留两位小数");return false}
        if(_days<10 || _days>90){alert("筹集天于为10-90天");return false;}
        if(!_reg_num.test(_days)){alert("请输入正确天数");return false;}
        if(_province == 0 || _province =='选择省份'){alert('请选择省份');return false;}
        if(_city == 0 || _city == '选择城市'){alert('请选择城市');return false;}
        if(_cate_id == false){alert("请选择类别");return false}
        if(_upload_image.length == 0 || _upload_image == null){
            alert("请上传一张项目封面");
            return false;
        }
        if(_brief.length <=0 || _brief.length > 75){alert("项目简介不能为空");return false;}
        var html =window.editor.html();
        $("#setp-textarea2").val(html);
        if($("#setp-textarea2").val().length <=0){
            alert("项目描述不能为空");
            return false;
        }
        $("#create-form").submit();
    });
//    模拟物流下拉
    $(".kuaidiMenu .getVal").on('click',function(){
       var data_val= $(this).attr('data-val');
       var data_key= $(this).attr('data-key');
        var val_ipt = $(this).parent(".dropdown-menu").siblings(".data_val");
        var key_ipt = $(this).parent(".dropdown-menu").siblings(".data_key");
        $(this).parent('.dropdown-menu').prev('[data-toggle]').find(".dr-text").text(data_val);
        val_ipt.val(data_val);
        key_ipt.val(data_key);
    });
    $("#goto-reg").on('click',function(){
        $("#login_dialog").modal('hide');
        $("#reg_dialog").modal('show');
    });

    $(".check-all").on('click',function(){
        var _h = $(".index-menu-nav").height();
        if(_h == '42'){
            $(".index-menu-nav").css('height','auto');
        }else{
            $(".index-menu-nav").css('height','42px');
        }
    });
    $(".is_num").on('blur',function(){
        var _reg =/^\d+$/;
        if(!_reg.test($(this).val())){
            alert("请输入数字")
        }
    });
    $(".is_money").on('blur',function(){
        var _reg = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
        if(!_reg.test($(this).val())){
            alert("请输入正确金额，最多保留两位小数")
        }else{
            $(this).val(parseFloat($(this).val()).toFixed(2));
        }
    });
    var _li = 7;
    var _li_total = $("#deal_cate_list li").length;
    var _li_width = $("#deal_cate_list li").width();
    $(".btn-pre").on('click',function(){
        var left = $("#deal_cate_list").position().left;
        if(left == 0 || left%90 != 0){
            return false;
        }
        $("#deal_cate_list").animate({'left':left + 90 + 'px'})
    })
    $(".btn-next").on('click',function(){
        var k = _li_total - _li;//根据总li条数判断移动多少条
        var move_li = -k*_li_width;//根据li宽度判断最终移动多少px
        var left = $("#deal_cate_list").position().left;
        if(left == move_li || left%90 != 0 ){return false;}
        $("#deal_cate_list").animate({'left':left - 90 + 'px'})
    })
});
//修改验证码
function code(sel){
    $(sel).attr('src', '/index/verify_code?rand=' + Math.random());
}

//修改手机ajax
sms ={
sms_validator:function(opt){
    $(opt.trigger).on('click',function(){

        var phone = $(opt.phone_sel).val();
        var _this = $(opt.trigger);
        if(_this.hasClass('ui-btn-disabled')){return false;}
        _this.addClass('ui-btn-disabled');
        $.post(opt.url,{mobile:phone,type:opt.type},function(data){
            if(data.status == 1){
                ajax.btnCountTime(_this,60);
            }else{
                alert(data.info);
                _this.removeClass('ui-btn-disabled');
            }
        },'json');
    })
}
};
sms.sms_validator({
    trigger:'#get-oldcode',
    phone_sel:'#oldphone',
    url:"/User/sms_validator",
    type:'old'
});
sms.sms_validator({
    trigger:'.get-newcode',
    phone_sel:'#newphone',
    url:"/User/sms_validator",
    type:'new'
});
sms.sms_validator({
    trigger:'.get-bind-code',
    phone_sel:'#phone',
    url:"/User/sms_validator",
    type:'bind'
});

var JPlaceHolder = {
    //检测
    _check : function(){
        return 'placeholder' in document.createElement('input');
    },
    //初始化
    init : function(){
        if(!this._check()){
            this.fix();
        }
    },
    //修复
    fix : function(){
        jQuery(':input[placeholder]').each(function(index, element) {
            var self = $(this), txt = self.attr('placeholder');
            if($(this).val().length > 0){return false;}
            self.wrap($('<div></div>').css({position:'relative', zoom:'1', border:'none', background:'none', padding:'none', margin:'none'}));
            var pos = self.position(), h = self.outerHeight(true), paddingleft = self.css('padding-left');
            var holder = $('<span></span>').text(txt).css({position:'absolute', left:pos.left, top:pos.top, height:h, lienHeight:h, paddingLeft:paddingleft, color:'#aaa'}).appendTo(self.parent());
            self.focusin(function(e) {
                holder.hide();
            }).focusout(function(e) {
                if(!self.val()){
                    holder.show();
                }
            });
            holder.click(function(e) {
                holder.hide();
                self.focus();
            });
        });
    }
};
//执行
jQuery(function(){
    JPlaceHolder.init();
});

